package im.elephas.androfan.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class ImageGetter {

	private final static String sdpath = "/sdcard/AndroFan/";
	private final static String datapath = "/data/data/im.elephas.androfan/avatar/";

	private final static char hexDigits[] = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private static void createAndWriteAvatar(String imageUrl) {
		try {
			String path = currentPath();

			File file = new File(path);
			if (!file.exists())
				file.mkdir();

			URL myFileUrl = new URL(imageUrl);

			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();

			String str = path + getMd5String(imageUrl);

			file = new File(str);
			if (!file.exists()) {
				file.mkdir();
			}

			file = new File(str + "/avatar.pic");
			if (!file.exists()) {
				file.createNewFile();
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buf = new byte[2048];

				int num = is.read(buf);
				while (num != -1) {
					fos.write(buf, 0, num);
					fos.flush();
					num = is.read(buf);
				}
				is.close();
				fos.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	private static String currentPath() {
		String path = sdpath;
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()))
			path = datapath;
		return path;
	}

	public static Bitmap getBitMap(String imageUrl) {
		try {
			if (!isImageFileExist(imageUrl))
				createAndWriteAvatar(imageUrl);
			return readAvatar(imageUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String getMd5String(String str)
			throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		byte tmp[] = md.digest();
		char s[] = new char[16 * 2];
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte byte0 = tmp[i];
			s[k++] = hexDigits[byte0 >>> 4 & 0xf];
			s[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(s);
	}

	private static boolean isImageFileExist(String imageUrl)
			throws NoSuchAlgorithmException {
		String path = currentPath();
		String str = path + getMd5String(imageUrl);

		File file = new File(str);
		if (file.exists()) {
			file = new File(str + "/avatar.pic");
			if (file.exists())
				return true;
			return false;
		}
		return false;
	}

	private static Bitmap readAvatar(String imageUrl) {
		Bitmap bm = null;
		String path = currentPath();

		try {
			String str = path + getMd5String(imageUrl) + "/avatar.pic";
			bm = BitmapFactory.decodeFile(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bm;
	}
}